#include "cryptoSocket.h"
#include "log.h"
#include "RC4.h"



CryptoSocket::CryptoSocket( const string server_ip, unsigned short server_port )
    :ip(server_ip),port(server_port),inited(false)
{
    Init();
}

CryptoSocket::~CryptoSocket()
{
    s.close();
}

int CryptoSocket::Send(void* buffer, int length, int flags /* = 0 */)
{
    if (buffer == NULL || length == 0)
    {
        return -1;
    }

    RC4 rc;
    int ret = -1;
    u_char* pBuf = (u_char*)buffer;

    rc.encrypt(pBuf, pBuf, length);
    try
    {
        int nSent = s.sendBytes(buffer,length,flags);
        if (nSent != length)
        {
            ret = -1;
        }
        else
        {
            ret = nSent;
        }
    }
    catch (Exception& e)
    {
        FLogger.information("error occurred while sending data...");
        FLogger.information(e.what());
        ret = -1;
    }

    return ret;
}

int CryptoSocket::Recv(void* buffer, int length, int flags /* = 0 */)
{
    if (buffer == NULL || length == 0)
    {
        return -1;
    }

    RC4 rc;
    int ret = -1;
    try
    {
        int nSent = s.receiveBytes(buffer,length,flags);
        if (nSent != length)
        {
            ret = -1;
        }


        u_char* pBuf = (u_char*)buffer;
        rc.encrypt(pBuf, pBuf, length);
        ret = nSent;
    }
    catch (Exception& e)
    {
        FLogger.information("error occurred while receiving data...");
        FLogger.information(e.what());
        ret = -1;
    }

    return ret;
}

void CryptoSocket::Init()
{
    try
    {
        SocketAddress addr(ip, port); 
        s.connect(addr);
        inited = true;
    }
    catch (Exception& e)
    {
        FLogger.information(e.what());
    }
}
